//
//  CTLogin.m
//  ConstellationTalk_0.1
//
//  Created by riley on 15/4/29.
//  Copyright (c) 2015年 riley chu. All rights reserved.
//

#import "CTLogin.h"
#import "CRSA.h"
#import "CTDeviceFunction.h"
#import "CTFile.h"
#import "CTAppInfo.h"
#import "CTRequestUtil.h"
#import "CTUrl.h"
#import "CTDebugManager.h"
#import "CTHeader.h"
#import "APService.h"

@implementation CTLogin

+(NSString *)token
{
    NSString * decryptStr;
    if ([CTFile isExistFile:@"token.text" doc:CTFileDocDocuments path:@"user"] == YES) {
        decryptStr = [[CRSA shareInstance] decryptByRsa:[CTFile getFile:@"token.text" fromDoc:CTFileDocDocuments fromPath:@"user"] withKeyType:KeyTypePublic];
    }else{
       decryptStr = [[CRSA shareInstance] decryptByRsa:[CTFile getFile:[NSString stringWithFormat:@"%@_visitor_token.text",[CTAppInfo appVersion]] fromDoc:CTFileDocDocuments fromPath:@"user"] withKeyType:KeyTypePublic];
    }
    NSString * encryptStr = [[CRSA shareInstance] encryptByRsa:decryptStr withKeyType:KeyTypePublic];
    NSString * deviceID = [CTDeviceFunction DeviceUDID];
    NSString * timeStamp = [CTDeviceFunction UnixTimestamp];
    NSString * newEncryptStr = [[CRSA shareInstance] encryptByRsa:[NSString stringWithFormat:@"%@&%@",deviceID,timeStamp] withKeyType:KeyTypePublic];
    NSString * str =[encryptStr stringByAppendingString:newEncryptStr];
   
    
    return str;
}




+(BOOL)isAppLicationFirstLunch
{
    if ([CTFile isExistFile:[NSString stringWithFormat:@"%@_visitor_token.text",[CTAppInfo appVersion]] doc:CTFileDocDocuments path:@"user"] == YES) {
        return NO;
    }
    return YES;
}
+(BOOL)isLoginState
{
    if ([CTFile isExistFile:[NSString stringWithFormat:@"%@_visitor_token.text",[CTAppInfo appVersion]] doc:CTFileDocDocuments path:@"user"] == YES || [CTFile isExistFile:@"token.text" doc:CTFileDocDocuments path:@"user"] == YES) {
        return YES;
    }
    return NO;
}
+(BOOL)isUserLoginState
{
    if ([CTFile isExistFile:@"token.text" doc:CTFileDocDocuments path:@"user"] == YES && [CTFile isExistFile:@"userInfo.plist" doc:CTFileDocDocuments path:@"user"] == YES) {
        return YES;
    }
    return NO;
}






//游客登录
+(void)visitorLoginWithsSuccessCompletionHandler:(requestSuccessedBlock)successBlock
                                   failedHandler:(requestFailedBlock)failedBlock
{
    NSMutableDictionary * param = [NSMutableDictionary dictionaryWithCapacity:0];
    @try {
        
        NSString * deviceID = [CTDeviceFunction DeviceUDID];
        NSString * clienttime = [CTDeviceFunction UnixTimestamp];
        NSString * openid = [[CRSA shareInstance] encryptByRsa:[CTDeviceFunction DeviceUDID] withKeyType:KeyTypePublic];
        
        [param setObject:deviceID forKey:@"deviceid"];
        [param setObject:clienttime forKey:@"clienttime"];
        [param setObject:openid forKey:@"openid"];
        
    }
    @catch (NSException *exception) {
        [CTDebugManager showErrorLogInfo:@"组装游客登录请求参数失败！！"];
    }
    
    [CTRequestUtil sendAsyPostRequest:CT_URL_ACCOUNTS_VISITOR(version) withParam:param withCompletionSuccessHandler:^(NSData *data) {
        
        CTVisitorLoginCompletionItem * item = [self parserData:data];
        if (item != nil) {
            successBlock(item);
        }
        else
        {
           failedBlock();
        }
        
        
    } withFailedHandler:^(NSError *error) {
        failedBlock();
    }];
}


//用户退出
+(void)exitAccountWithsSuccessCompletionHandler:(exitSuccessedBlock)successBlock
                                  failedHandler:(exitFailedBlock)failedBlock
{
    [CTFile removeFile:@"token.text" fromDoc:CTFileDocDocuments fromPath:@"user"];
    [CTFile removeFile:@"userInfo.plist" fromDoc:CTFileDocDocuments fromPath:@"user"];
    [CTFile removeFile:@"userType.text" fromDoc:CTFileDocDocuments fromPath:@"user"];
    [CTFile removeFile:@"userPhoneNumber.text" fromDoc:CTFileDocDocuments fromPath:@"user"];
    [CTFile removeFile:@"userCreated.text" fromDoc:CTFileDocDocuments fromPath:@"user"];
    
    
    [CTFile removeFile:@"homepage" fromDoc:CTFileDocLibrary fromPath:@"cacheData"];
    [CTFile removeFile:@"discovery" fromDoc:CTFileDocLibrary fromPath:@"cacheData"];
    [CTFile removeFile:@"user" fromDoc:CTFileDocLibrary fromPath:@"cacheData"];
    
    [CTFile removeFile:@"switch.text" fromDoc:CTFileDocLibrary fromPath:@"cacheData/message/switch"];
    
    
    //设置消息，取消当前用户与设备的绑定
    NSString * alisaStr = @"picopico_nil_user";
    [APService setAlias:alisaStr callbackSelector:nil object:nil];
    
    successBlock();
    
    [[NSNotificationCenter defaultCenter] postNotificationName:CTExitSuccessNotification object:nil];
}



#pragma mark - data parser -

+(CTVisitorLoginCompletionItem *)parserData:(NSData *)resultData
{
    
    CTVisitorLoginCompletionItem * itm;
    
    @try {
        
        NSError * error;
        
        id jsonObject = [NSJSONSerialization
                         JSONObjectWithData:resultData
                         options:NSJSONReadingAllowFragments
                         error:&error];
        if (jsonObject != nil && error == nil){
            
            if ([jsonObject isKindOfClass:[NSDictionary class]]){
                
                NSDictionary *deserializedDictionary = (NSDictionary *)jsonObject;
                
                NSString * errCode = [NSString stringWithFormat:@"%@",(NSString *)[deserializedDictionary objectForKey:@"error_code"]];
                if ([errCode isEqualToString:@"0"]) {
                    
                    itm = [[CTVisitorLoginCompletionItem alloc] init];
                    
                    NSDictionary * infoDic = [deserializedDictionary objectForKey:@"info"];
                    itm.token = [NSString stringWithFormat:@"%@",[infoDic objectForKey:@"token"]];
                    
                    
                    //存入文件
                    
                    //visitor token:
                    [CTFile cacheFile:itm.token
                             fileName:[NSString stringWithFormat:@"%@_visitor_token.text",[CTAppInfo appVersion]]
                              saveDoc:CTFileDocDocuments
                             savePath:@"user"];
                    
                    
                }
                
            }
        }
        else
        {
            [CTDebugManager showErrorLogInfo:@"解析游客登录数据失败！！"];
        }
    }
    @catch (NSException *exception) {
        [CTDebugManager showErrorLogInfo:@"解析游客登录数据失败！！"];
    }
    
    return itm;
    
}


@end
